package dev.tools.design.patterns.state;

import dev.tools.Base;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 02-10-2013
 * Time: 18:18
 */
public class Context<TContext extends Context<TContext, TState>, TState extends State<TContext, TState>> extends Base {
    private TState state;

    protected Context(TState state) {
        this.state = state;
    }

    public TState getState() {
        return state;
    }

    public void setState(TState state) {
        if(this.state == state)
            return;
        TState oldState = this.state;
        this.state = state;

        System.out.println(this + ": " + oldState + " --> " + state);

        if (!handlers.containsKey(state))
            return;

        StateChanged stateChanged = new StateChanged(this, oldState, state);

        for (IStateHandler<TContext, TState> handler : handlers.get(state))
            handler.update((TContext) this, stateChanged);
    }

    private final Map<TState, Set<IStateHandler<TContext, TState>>> handlers = new LinkedHashMap<>();

    public TContext addHandler(IStateHandler<TContext, TState> handler, TState... states) {
        for (TState state : states){
            if (!handlers.containsKey(state))
                handlers.put(state, new LinkedHashSet<IStateHandler<TContext, TState>>());

            handlers.get(state).add(handler);
        }

        return (TContext) this;
    }

    public boolean isState(TState state) {
        return this.state == state;
    }
}
